import router from './router'
import store from './store'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login'] // 白名单

router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = to.meta.title ? `${to.meta.title} - IoT管理平台` : 'IoT管理平台'

  const hasToken = getToken()
  
// 调试日志
//   console.log('当前路由:', $router.currentRoute.value)
// console.log('用户状态:', $store.state.user)
// console.log('有效路由:', $router.getRoutes())

  try {
    // 白名单处理
    if (whiteList.includes(to.path)) {
      if (hasToken) {
        next({ path: '/' })
        NProgress.done()
        return
      }
      next()
      NProgress.done()
      return
    }

    // 无token情况
    if (!hasToken) {
      console.warn('无token访问受限路由')
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
      NProgress.done()
      return
    }

    // 已登录状态
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
      return
    }

    // 获取用户信息
    if (!store.state.user.infoLoaded) {
      ///console.log('开始获取用户信息...')
      await store.dispatch('user/getInfo')
      //console.log('用户信息获取完成:', store.state.user)
    }

    // 权限验证
    if (store.getters.permissions.length === 0) {
      //console.error('用户无有效权限')
      ElMessage.error('您还没权限，请先分配权限！')
      next(false)
      NProgress.done()
      return
    }

    // 路由存在性检查
    if (to.matched.length === 0) {
      console.warn('路由未匹配:', to.path)
      next('/404')
      NProgress.done()
      return
    }

    console.log('允许访问:', to.path)
    next()
  } catch (error) {
    console.error('路由守卫异常:', error)
    await store.dispatch('user/resetToken')
    ElMessage.error(error?.message || '系统错误')
    next(`/login?redirect=${encodeURIComponent(to.fullPath)}`)
  } finally {
    console.groupEnd()
    NProgress.done()
  }
}) 